package com.example.base_kotlin_xml.view

import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.LogUtils
import com.example.base_kotlin_xml.R
import com.example.base_kotlin_xml.databinding.FragmentLoopTimerBinding
import com.example.base_model.utils.LoopTimer
import com.example.base_model.utils.loopTimer
import com.example.base_model.view.BaseFragment
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel

/**
 * @Author: jiangKunKun
 * @CreateDate: 2025/7/30
 * @Description: 循环
 * @SpittingGrooves
 */
@AndroidEntryPoint
class LoopTimerFragment : BaseFragment<FragmentLoopTimerBinding>() {
    private val serviceScope = CoroutineScope(Dispatchers.Main + SupervisorJob())
    private var timerOne: LoopTimer? = null
    private var timerTwo: LoopTimer? = null

    override fun initObservers() {
        // 循环
        timerOne = serviceScope.loopTimer()
            .setParams(delay = 1000, interval = 1000, maxCount = 5)
            .onTick {
                LogUtils.d("serviceScope.loopTimer 循环体 注意手动取消 次数${it}")
            }
            .onComplete {
                LogUtils.d("serviceScope.loopTimer 循环结束 注意手动取消")
            }
        timerTwo = lifecycleScope.loopTimer()
            .setParams(delay = 0, interval = 500, maxCount = 5)
            .onTick {
                LogUtils.d("lifecycleScope.loopTimer 循环体 不需要手动取消${it}")
            }
            .onComplete {
                LogUtils.d("lifecycleScope.loopTimer 循环结束 不需要手动取消")
            }
    }

    override fun initClickEvents() {
        // 开始
        mBinding.btnLoopTimerStart.setOnClickListener {
            timerTwo?.start()
        }
        // 暂停
        mBinding.btnLoopTimerPause.setOnClickListener {
            timerTwo?.pause()
        }
        // 继续
        mBinding.btnLoopTimerResume.setOnClickListener {
            timerTwo?.resume()
        }
        // 停止
        mBinding.btnLoopTimerStop.setOnClickListener {
            timerTwo?.stop()
        }
        mBinding.btnLoopTimer2.setOnClickListener {
            timerOne?.start()
        }
    }

    override fun initData() {
    }

    override fun attachLayoutRes(): Int = R.layout.fragment_loop_timer

    override fun onDestroy() {
        super.onDestroy()
        timerOne?.stop()
        serviceScope.cancel()
    }
}